package service

import (
	"errors"
	"gin-wave-im/global"
	"gin-wave-im/model"
	"gin-wave-im/model/request"
	"gin-wave-im/util"
)

// 创建群聊
func CreateCommunity(community request.CreateCommunity, userId uint64) (error, uint64) {
	picLen := len(community.Icon)
	if picLen > 0 {
		hostLen := len(global.GnConfig.System.ImgHost)
		community.Icon = community.Icon[hostLen:]
	}
	newCommunity := model.Community{
		Name:     community.Name,
		OwnerId:  userId,
		Icon:     community.Icon,
		Intro:     community.Intro,
	}
	err := global.GnDb.Create(&newCommunity).Error
	dstId := newCommunity.ID

	return err,dstId
}

// 加入群聊
func JoinCommunity(userId uint64, dstId uint64) error {
	db := global.GnDb
	var dst model.Community
	db.Where("id = ?", dstId).First(&dst)
	if dst.ID == 0 {
		return errors.New("该群聊不存在！")
	}
	//判断是否已经加入了群聊
	tmp := model.Contact{}
	db.Where("owner_id = ?", userId).Where("dst_id = ?", dstId).Where("cate = ?", model.CONCAT_CATE_COMMUNITY).First(&tmp)
	if tmp.ID > 0 {
		return errors.New("您已加入此群聊啦！")
	}

	myContact := model.Contact{
		OwnerId: userId,
		DstId:   dstId,
		Cate:    model.CONCAT_CATE_COMMUNITY,
	}
	err := global.GnDb.Create(&myContact).Error

	return err
}

// 获得用户已加入群聊的id
func CommunityIds(userId uint64) ([]uint64, error) {
	tmp := []model.Contact{}
	var dstIds []uint64
	global.GnDb.Where("owner_id = ?", userId).Where("cate = ?", model.CONCAT_CATE_COMMUNITY).Find(&tmp)
	if len(tmp) == 0 {
		return dstIds,errors.New("没有群聊！")
	}
	for _,dst := range tmp{
		dstIds = append(dstIds, dst.DstId)
	}

	return dstIds,nil
}

// 群聊信息
func CommunityInfo(id uint64) (community model.Community, err error) {
	community = model.Community{}
	err = global.GnDb.First(&community, id).Error
	community.Icon = util.TransformImageUrl(community.Icon)

	return community,err
}

// 群聊列表
func CommunityList(ids []uint64) ([]model.Community, error) {
	communities := []model.Community{}
	for _, id := range ids {
		tmp,err := CommunityInfo(id)
		if err == nil {
			communities = append(communities, tmp)
		}
	}
	return communities,nil
}

// 获得群聊包含哪些用户
func MemberList(dstId uint64) ([]uint64, error) {
	tmp := []model.Contact{}
	var userIds []uint64
	global.GnDb.Where("dst_id = ?", dstId).Where("cate = ?", model.CONCAT_CATE_COMMUNITY).Find(&tmp)
	if len(tmp) == 0 {
		return userIds,errors.New("没有群聊！")
	}
	for _,dst := range tmp{
		userIds = append(userIds, dst.OwnerId)
	}

	return userIds,nil
}

// 获得某个用户加入了哪些群聊
func SearchCommunityIds(userId uint64) ([]uint64, error) {
	tmp := []model.Contact{}
	var comIds []uint64
	global.GnDb.Where("owner_id = ?", userId).Where("cate = ?", model.CONCAT_CATE_COMMUNITY).Find(&tmp)
	if len(tmp) == 0 {
		return comIds,errors.New("没有群聊！")
	}
	for _,dst := range tmp{
		comIds = append(comIds, dst.DstId)
	}

	return comIds,nil
}